package cn.edu.baiyunu.myapplication.data.repository

import cn.edu.baiyunu.myapplication.data.TestDataGenerator
import cn.edu.baiyunu.myapplication.data.dao.CategoryDao
import cn.edu.baiyunu.myapplication.data.model.Category
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import java.util.UUID
import javax.inject.Inject
import javax.inject.Singleton

/**
 * CategoryRepository接口的实现类
 */
@Singleton
class CategoryRepositoryImpl @Inject constructor(
    private val categoryDao: CategoryDao
) : CategoryRepository {
    
    override fun getExpenseCategories(): Flow<List<Category>> {
        return categoryDao.getCategoriesByType("expense")
    }
    
    override fun getIncomeCategories(): Flow<List<Category>> {
        return categoryDao.getCategoriesByType("income")
    }
    
    override fun getCategoryById(id: String): Flow<Category?> {
        return categoryDao.getAllCategories().map { categories ->
            categories.find { it.id == id }
        }
    }
    
    override suspend fun addCategory(category: Category) {
        categoryDao.insertCategory(category)
    }
    
    override suspend fun updateCategory(category: Category) {
        categoryDao.updateCategory(category)
    }
    
    override suspend fun deleteCategory(id: String) {
        categoryDao.deleteCategoryById(id)
    }
    
    override suspend fun initDefaultCategories() {
        // 检查是否已经有分类
        val categories = categoryDao.getAllCategories().first()
        if (categories.isNotEmpty()) {
            return // 已经有分类，不需要初始化
        }
        
        // 使用测试数据生成器获取默认分类
        val expenseCategories = TestDataGenerator.getDefaultExpenseCategories()
        val incomeCategories = TestDataGenerator.getDefaultIncomeCategories()
        
        // 批量插入所有默认分类
        val allCategories = expenseCategories + incomeCategories
        categoryDao.insertCategories(allCategories)
    }
} 